<template>
  <div class="advanced-search-container">
    <el-form :model="searchForm" label-width="80px" class="advanced-search-form">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item label="漏洞名称">
            <el-input 
              v-model="searchForm.name" 
              placeholder="输入漏洞名称关键词" 
              clearable
              @input="handleInputChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item label="风险等级">
            <el-select 
              v-model="searchForm.riskLevel" 
              placeholder="选择风险等级" 
              clearable
              @change="handleInputChange"
            >
              <el-option label="高风险" value="high" />
              <el-option label="中风险" value="medium" />
              <el-option label="低风险" value="low" />
              <el-option label="信息" value="info" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item label="漏洞类型">
            <el-select 
              v-model="searchForm.vulnerabilityType" 
              placeholder="选择漏洞类型" 
              clearable
              @change="handleInputChange"
            >
              <el-option v-for="type in vulnerabilityTypes" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item label="影响范围">
            <el-input 
              v-model="searchForm.affectedScope" 
              placeholder="输入影响范围关键词" 
              clearable
              @input="handleInputChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item label="发现时间">
            <el-date-picker
              v-model="searchForm.discoveryDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleInputChange"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8">
          <el-form-item label="修复状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="选择修复状态" 
              clearable
              @change="handleInputChange"
            >
              <el-option label="未修复" value="unfixed" />
              <el-option label="修复中" value="fixing" />
              <el-option label="已修复" value="fixed" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <div v-if="showAdvancedOptions" class="advanced-options">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="CVSS分数">
              <el-input-number
                v-model="searchForm.minCVSS"
                :min="0"
                :max="10"
                placeholder="最小值"
                @change="handleInputChange"
              />
              <span style="margin: 0 10px;">-</span>
              <el-input-number
                v-model="searchForm.maxCVSS"
                :min="0"
                :max="10"
                placeholder="最大值"
                @change="handleInputChange"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="CVE编号">
              <el-input 
                v-model="searchForm.cveId" 
                placeholder="输入CVE编号" 
                clearable
                @input="handleInputChange"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="扫描工具">
              <el-select 
                v-model="searchForm.scanner" 
                placeholder="选择扫描工具" 
                clearable
                @change="handleInputChange"
              >
                <el-option v-for="tool in scanningTools" :key="tool.value" :label="tool.label" :value="tool.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="资产类型">
              <el-select 
                v-model="searchForm.assetType" 
                placeholder="选择资产类型" 
                clearable
                @change="handleInputChange"
              >
                <el-option label="服务器" value="server" />
                <el-option label="Web应用" value="web" />
                <el-option label="移动应用" value="mobile" />
                <el-option label="API" value="api" />
                <el-option label="数据库" value="database" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <div class="search-actions">
        <el-button 
          type="primary" 
          @click="handleSearch"
          icon="el-icon-search"
          :loading="searching"
        >
          搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="text" @click="toggleAdvancedOptions">
          {{ showAdvancedOptions ? '收起高级选项' : '展开高级选项' }}
          <i :class="`el-icon-arrow-${showAdvancedOptions ? 'up' : 'down'}`"></i>
        </el-button>
        <el-button 
          v-if="hasActiveFilters" 
          type="text" 
          @click="clearActiveFilters"
          class="filter-tag"
        >
          <el-tag
            closable
            @close="clearActiveFilters"
            effect="dark"
          >
            {{ activeFiltersCount }} 个筛选条件
          </el-tag>
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { ref, computed, reactive } from 'vue'

export default {
  name: 'AdvancedSearch',
  emits: ['search', 'reset', 'filters-changed'],
  setup(props, { emit }) {
    // 漏洞类型列表
    const vulnerabilityTypes = ref([
      { label: 'SQL注入', value: 'sql_injection' },
      { label: '跨站脚本(XSS)', value: 'xss' },
      { label: '跨站请求伪造(CSRF)', value: 'csrf' },
      { label: '命令注入', value: 'command_injection' },
      { label: '身份认证缺陷', value: 'auth_bypass' },
      { label: '授权问题', value: 'authorization' },
      { label: '敏感信息泄露', value: 'info_disclosure' },
      { label: '文件包含', value: 'file_inclusion' },
      { label: '不安全配置', value: 'misconfiguration' },
      { label: '缓冲区溢出', value: 'buffer_overflow' },
      { label: '不安全反序列化', value: 'deserialization' },
      { label: '代码注入', value: 'code_injection' },
      { label: '点击劫持', value: 'clickjacking' },
      { label: '路径遍历', value: 'path_traversal' },
      { label: '其他', value: 'other' }
    ])
    
    // 扫描工具列表
    const scanningTools = ref([
      { label: 'Nessus', value: 'nessus' },
      { label: 'OpenVAS', value: 'openvas' },
      { label: 'Burp Suite', value: 'burp' },
      { label: 'OWASP ZAP', value: 'zap' },
      { label: 'SQLmap', value: 'sqlmap' },
      { label: 'Nuclei', value: 'nuclei' },
      { label: '自定义工具', value: 'custom' }
    ])
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      riskLevel: '',
      vulnerabilityType: '',
      affectedScope: '',
      discoveryDate: null,
      status: '',
      minCVSS: null,
      maxCVSS: null,
      cveId: '',
      scanner: '',
      assetType: ''
    })
    
    const showAdvancedOptions = ref(false)
    const searching = ref(false)
    
    // 计算属性：是否有活跃的筛选条件
    const hasActiveFilters = computed(() => {
      return Object.values(searchForm).some(val => {
        if (val === null || val === undefined || val === '') return false
        if (Array.isArray(val) && val.length === 0) return false
        return true
      })
    })
    
    // 计算活跃筛选条件数量
    const activeFiltersCount = computed(() => {
      return Object.values(searchForm).filter(val => {
        if (val === null || val === undefined || val === '') return false
        if (Array.isArray(val) && val.length === 0) return false
        return true
      }).length
    })
    
    // 处理搜索
    const handleSearch = async () => {
      searching.value = true
      try {
        // 构建搜索参数
        const searchParams = { ...searchForm }
        
        // 转换日期格式
        if (searchParams.discoveryDate && searchParams.discoveryDate.length === 2) {
          searchParams.discoveryDate = {
            start: searchParams.discoveryDate[0],
            end: searchParams.discoveryDate[1]
          }
        }
        
        // 发出搜索事件
        emit('search', searchParams)
      } catch (error) {
        console.error('搜索出错:', error)
      } finally {
        searching.value = false
      }
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      showAdvancedOptions.value = false
      emit('reset')
    }
    
    // 切换高级选项显示
    const toggleAdvancedOptions = () => {
      showAdvancedOptions.value = !showAdvancedOptions.value
    }
    
    // 清空活跃筛选条件
    const clearActiveFilters = () => {
      handleReset()
    }
    
    // 处理输入变化，发出筛选条件变更事件
    const handleInputChange = () => {
      emit('filters-changed', { ...searchForm })
    }
    
    // 导出方法供父组件调用
    const resetSearch = () => {
      handleReset()
    }
    
    const setSearchCriteria = (criteria) => {
      Object.keys(criteria).forEach(key => {
        if (searchForm.hasOwnProperty(key)) {
          searchForm[key] = criteria[key]
        }
      })
      handleSearch()
    }
    
    return {
      searchForm,
      showAdvancedOptions,
      searching,
      vulnerabilityTypes,
      scanningTools,
      hasActiveFilters,
      activeFiltersCount,
      handleSearch,
      handleReset,
      toggleAdvancedOptions,
      clearActiveFilters,
      handleInputChange,
      // 导出方法
      resetSearch,
      setSearchCriteria
    }
  }
}
</script>

<style scoped>
.advanced-search-container {
  background-color: var(--bg-color, #ffffff);
  border-radius: 8px;
  padding: 16px;
  box-shadow: var(--box-shadow, 0 2px 12px rgba(0, 0, 0, 0.1));
  transition: all 0.3s ease;
}

.advanced-search-form {
  margin-bottom: 0;
}

.search-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.advanced-options {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed var(--border-color, #ebeef5);
  transition: all 0.3s ease;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.filter-tag {
  margin-left: auto;
}

/* 暗色模式适配 */
:global(.dark-mode) .advanced-search-container {
  background-color: var(--bg-color, #1f2937);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
}

:global(.dark-mode) .advanced-options {
  border-top-color: #374151;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-actions {
    justify-content: center;
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-tag {
    margin-left: 0;
    margin-top: 8px;
    text-align: center;
  }
}
</style>